package net.jiastudy.web.rest.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.baomidou.mybatisplus.plugins.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import net.jiastudy.biz.UserImporterVerifyHandler;
import net.jiastudy.biz.datasync.DataSyncService;
import net.jiastudy.biz.datasync.LeaderImporter;
import net.jiastudy.biz.datasync.UserImporter;
import net.jiastudy.biz.sys.util.ReaderPermissionConfig;
import net.jiastudy.biz.user.LeaderImporterVerifyHander;
import net.jiastudy.biz.user.entity.User;
import net.jiastudy.biz.user.service.RoleService;
import net.jiastudy.biz.user.service.UserService;
import net.jiastudy.core.base.BaseController;
import net.jiastudy.core.common.validgroup.Create;
import net.jiastudy.core.common.validgroup.Update;
import net.jiastudy.core.exception.NotFoundException;
import net.jiastudy.core.exception.ServiceException;
import net.jiastudy.core.utils.UploadUtil;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/users")
@Api(value = "UserController  用户管理")
public class UserController extends BaseController {
	@Resource
	private UserService userService;
	@Resource
	private RoleService roleService;
	@Value("${upload.path.base}")
	private String basePath;
	@Value("${powerby}")
	private String powerby;
	@Value("${toptask.government}")
	private Boolean toptaskGovernment;
	@Resource
	private DataSyncService dataSyncService;

	@RequestMapping(path = "/{id}", method = RequestMethod.GET)
	@ApiOperation(value = "查询用户", notes = "根据url的id来查询用户信息")
	public User get(@PathVariable Long id) {
		User user = userService.getUserById(id);
		if (null == user) {
			throw new NotFoundException("404", "用户不存在");
		}
		user.setRoles(roleService.findRolesByUserId(user.getId()));
		return user;
	}

	@RequestMapping(path = "/checkusername", method = RequestMethod.GET)
	@ApiOperation(value = "检查用户名是否重复", notes = "根据用户名检查是否重复,true为可用，false为不可用")
	public boolean checkUserName(@RequestParam(required = true) String username, Long currentUserId) {
		return !userService.checkUsernameExists(username, currentUserId);
	}

	@RequestMapping(method = RequestMethod.POST)
	@ApiOperation(value = "新增用户", notes = "根据提交的数据创建新用户")
	public User create(@Validated({ Create.class }) @RequestBody User user) {
		return userService.createUser(user);
	}

	@RequestMapping(path = "/{id}", method = RequestMethod.PUT)
	@ApiOperation(value = "编辑用户信息")
	public User edit(@PathVariable @ApiParam(name = "id", value = "用户ID", required = true) Long id,
			@Validated({ Update.class }) @RequestBody User user) {
		user.setId(id);
		return userService.updateUser(user);
	}

	@RequestMapping(path = "/current", method = RequestMethod.GET)
	@ApiOperation(value = "获取当前登录用户信息")
	public User getCurrentUserInfo() {
		User user = this.getCurrentUser();
		user.setRoles(roleService.findRolesByUserId(user.getId()));

		if (user.isAdmin()) {
			user.setPermissions(ReaderPermissionConfig.getPermissionCodes(ReaderPermissionConfig.readerConfig()));
		} else {
			user.setPermissions(roleService.findPermissionsByUserId(user.getId()));
		}

		user.setPowerby(this.powerby);
		user.setToptaskGovernment(this.toptaskGovernment);

		return user;
	}

	@RequestMapping(path = "/changepassword", method = RequestMethod.PUT)
	@ApiOperation(value = "修改当前用户的密码")
	public boolean changePassword(@RequestBody @ApiParam Map<String, String> params) {
		User user = this.getCurrentUser();
		String oldPassword = params.get("oldPassword");
		String newPassword = params.get("newPassword");
		return userService.changePassword(user.getId(), oldPassword, newPassword);
	}

	@RequestMapping(path = "/{id}/resetpassword", method = RequestMethod.PUT)
	@ApiOperation(value = "管理员重置指定用户的的密码")
	public boolean resetPassword(@PathVariable Long id, @RequestBody @ApiParam Map<String, String> params) {
		String password = params.get("password");
		return userService.changePassword(id, password);
	}

	@RequestMapping(method = RequestMethod.GET)
	@ApiOperation(value = "分页检索用户列表", notes = "根据查询条件查询用户")
	public Page<User> page(@RequestParam Map<String, String> conditions,
			@PageableDefault(value = 50, sort = { "id" }, direction = Sort.Direction.DESC) Pageable pageable) {
		Page<User> page = new Page<>(pageable.getPageNumber(), pageable.getPageSize());
		Sort sort = pageable.getSort();
		return userService.pageUsers(page, conditions, sort);
	}

	@RequestMapping(path = "/{id}/updateuserrole", method = RequestMethod.PUT)
	public Boolean updateUserRole(@PathVariable Long id, @RequestBody Map<String, List<Long>> conditions) {
		User user = userService.getUserById(id);
		List<Long> roleIds = conditions.get("roleIds");
		return roleService.addUserRoles(user, roleIds);
	}

	@RequestMapping(path = "/search", method = RequestMethod.GET)
	@ApiOperation(value = "根据姓名等搜专业负责人")
	public List<User> findByEmployeeNumber(String keywords) {
		Page<User> page = new Page<>(1, 20);
		Map<String, String> conditions = new HashMap<>();
		conditions.put("keywords", keywords);
		return userService.pageUsers(page, conditions, null).getRecords();
	}

	@RequestMapping(path = "/import", method = RequestMethod.POST)
	@ApiOperation(value = "导入用户")
	public boolean importUser(@RequestParam("file") MultipartFile file) {
		if (file.isEmpty() || file.getSize() == 0) {
			return true;
		}
		Date now = new Date();
		String fileName = file.getOriginalFilename();
		fileName = "/" + now.getTime() + fileName;

		String filePath = UploadUtil.TEMP_PATH + UploadUtil.makeFileDir(now);
		boolean bool = UploadUtil.mkdirs(basePath + filePath);
		if (!bool) {
			logger.error("创建目录失败，请检查权限");
			throw new ServiceException("500", "创建目录失败，请检查权限");
		}
		java.io.File dest = new java.io.File(basePath + filePath + fileName);
		try {
			file.transferTo(dest);
		} catch (IllegalStateException | IOException e) {
			logger.error("文件上传出错了：", e);
		}

		ImportParams params = new ImportParams();
		params.setHeadRows(1);
		params.setVerifyHandler(new UserImporterVerifyHandler());
		ExcelImportResult<UserImporter> list = ExcelImportUtil.importExcelMore(
				dest, UserImporter.class, params);
		userService.importUsers(list.getList());

		return true;
	}

	@RequestMapping(path = "/template", method = RequestMethod.GET)
	@ApiOperation(value = "下载导入模板")
	public void downloadTemplate(HttpServletResponse response) throws IOException  {
		List<UserImporter> list = new ArrayList<>();
		UserImporter userImporter = new UserImporter();
		userImporter.setDeptName("教务处");
		userImporter.setGender("男");
		userImporter.setNumber("2018982");
		userImporter.setName("张三");
		list.add(userImporter);
		ExportParams params = new ExportParams();
		Workbook workbook = ExcelExportUtil.exportExcel(params, UserImporter.class, list);

		UploadUtil.setFileDownloadHeader(response, "用户导入模板.xls");
		workbook.write(response.getOutputStream());
	}

	@RequestMapping(path = "/leader/template", method = RequestMethod.GET)
	@ApiOperation(value = "下载部门负责人导入模板")
	public void downloadLeaderTemplate(HttpServletResponse response) throws IOException  {
		List<LeaderImporter> list = new ArrayList<>();
		LeaderImporter leaderImport = new LeaderImporter();
		leaderImport.setNumber("2018982");
		ExportParams params = new ExportParams();
		Workbook workbook = ExcelExportUtil.exportExcel(params, LeaderImporter.class, list);

		UploadUtil.setFileDownloadHeader(response, "部门负责人导入模板.xls");
		workbook.write(response.getOutputStream());
	}

	@RequestMapping(path = "/leader/import", method = RequestMethod.POST)
	@ApiOperation(value = "导入部门负责人")
	public boolean importLeader(@RequestParam("file") MultipartFile file) {
		if (file.isEmpty() || file.getSize() == 0) {
			return true;
		}
		Date now = new Date();
		String fileName = file.getOriginalFilename();
		fileName = "/" + now.getTime() + fileName;

		String filePath = UploadUtil.TEMP_PATH + UploadUtil.makeFileDir(now);
		boolean bool = UploadUtil.mkdirs(basePath + filePath);
		if (!bool) {
			logger.error("创建目录失败，请检查权限");
			throw new ServiceException("500", "创建目录失败，请检查权限");
		}
		java.io.File dest = new java.io.File(basePath + filePath + fileName);
		try {
			file.transferTo(dest);
		} catch (IllegalStateException | IOException e) {
			logger.error("文件上传出错了：", e);
		}

		ImportParams params = new ImportParams();
		params.setHeadRows(1);
		params.setVerifyHandler(new LeaderImporterVerifyHander());
		ExcelImportResult<LeaderImporter> list = ExcelImportUtil.importExcelMore(
				dest, LeaderImporter.class, params);
		userService.batchSetLeader(list.getList());

		return true;
	}

	@RequestMapping(path = "/test", method = RequestMethod.GET)
	@ApiOperation(value = "分页检索用户列表", notes = "根据查询条件查询用户")
	public void test() {
		dataSyncService.syncAll();
	}

}
